import org.apache.ibatis.datasource.pooled.PooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cxx
 * @create 2020-05-29 17:49
 **/
public class RouteDataSource extends PooledDataSource {

    private final static Map<String, DataSource> map = new HashMap<> ();

    private DataSource dataSource;

    private static final ThreadLocal<String> ROUTE_MAP = new ThreadLocal<> ();

    @Override
    public Connection getConnection() throws SQLException {
        DataSource ds = map.getOrDefault (ROUTE_MAP.get (), dataSource);
        return ds.getConnection ();
    }

    public void setDefaultDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void addDataSource(String id,DataSource ds){
        map.put (id,ds);
    }

    public static void removeRoute(){
        ROUTE_MAP.remove ();
    }

    public static void addRoute(String id){
        ROUTE_MAP.set (id);
    }


}
